package top.healthylife.service.impl;/*
 *@Author GaoZeXi
 *@Created time 2020/4/24 23:10
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import top.healthylife.domain.Permission;
import top.healthylife.domain.Role;
import top.healthylife.domain.User;
import top.healthylife.entity.PageResult;
import top.healthylife.entity.QueryPageBean;
import top.healthylife.mapper.RoleMapper;
import top.healthylife.mapper.UserMapper;
import top.healthylife.service.RoleService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        int currentPage = queryPageBean.getCurrentPage();
        int pageSize = queryPageBean.getPageSize();
        //开启分页
        PageHelper.startPage(currentPage, pageSize);
        String queryString = queryPageBean.getQueryString();
        Page<Role> page = roleMapper.selectByCondition(queryString);
        System.out.println("总记录==============" + page.getTotal());
        System.out.println("结果集==============" + page.getResult());
        return new PageResult(page.getTotal(), page.getResult());

    }

    @Override
    public List<Role> findAll() {
        return null;
    }


    @Override
    public Set<Role> findRolesByUser(User user) {
        return roleMapper.findByUserId(user.getId());
    }

    @Override
    public void updateById(Permission permission) {

    }

    @Override
    public void deleteById(Integer id) {
        roleMapper.deleteById(id);
    }

    @Override
    public void add(Role role, Integer[] permissionIds) {
        roleMapper.add(role);
        Integer id = role.getId();
        setRoleAndPermission(id, permissionIds);
    }

    @Override
    public Role findById(Integer roleId) {
        return roleMapper.findById(roleId);

    }

    private void setRoleAndPermission(Integer id, Integer[] permissionIds) {
        if (permissionIds != null && permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {
                Map<String, Integer> map = new HashMap<>(16);
                map.put("role_id", id);
                map.put("permission_id", permissionId);
                roleMapper.setRoleAndPermission(map);
            }
        }
    }
}
